import {
  Component,
  EventEmitter,
  Injector,
  Input,
  OnInit,
  Output,
} from '@angular/core';
import {
  EditionServiceProxy,
  SubscribableEditionComboboxItemDto,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';

@Component({
  selector: 'edition-combo',
  templateUrl: './edition-combo.component.html',
  styles: [],
})
export class EditionComboComponent extends AppComponentBase implements OnInit {
  editions: SubscribableEditionComboboxItemDto[] = [];
  @Input() addNotAssignedItem: boolean;
  @Input() addAllItem: boolean;
  @Input() placeholder: string;
  @Input() selectedEdition: SubscribableEditionComboboxItemDto = undefined;
  @Output() selectedEditionChange: EventEmitter<
    SubscribableEditionComboboxItemDto
    > = new EventEmitter<SubscribableEditionComboboxItemDto>();

  private _editionId: string;
  @Input() editionId: string;

  constructor(
    private _editionService: EditionServiceProxy,
    injector: Injector,
  ) {
    super(injector);
  }

  ngOnChanges(): void {
    this._editionService
      .getEditionComboboxItems(
        0,
        this.addAllItem,
        false,
        this.addNotAssignedItem,
      )
      .subscribe(editions => {
        this.editions = editions;
        this._editionId = this.editionId;
        this.autoSelect();
      });
  }

  ngOnInit(): void { }

  autoSelect() {
    if (!this.editions || !this._editionId) {
      return;
    }
    this.selectedEdition = this.editions.find(
      item => item.value == this._editionId,
    );
    if (this.selectedEditionChange) {
      this.selectedEditionChange.emit(this.selectedEdition);
    }
  }
}
